package com.arges.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CpuUsage {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder("top", "-b", "-n", "1");
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("Cpu(s)")) {
                String[] cpuInfo = line.split(",\\s+");
                String idleCpu = cpuInfo[3].replaceAll("%id,", "");
                float cpuUsage = 100 - Float.parseFloat(idleCpu);
                System.out.println("CPU使用率：" + cpuUsage);
            }
        }
        process.waitFor();
    }
}